package com.infocollect.project.api.service.impl;

import com.infocollect.project.api.enums.IBaseEnum;
import com.infocollect.project.api.req.BatchDicEnumReq;
import com.infocollect.project.api.service.ICommService;
import com.infocollect.project.api.vo.DictionaryEnumVO;
import com.infocollect.project.form.vo.R;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CommServiceImpl implements ICommService {

    public R<List<DictionaryEnumVO>> getDictionaryEnum(String menuType) {
        try {
            List<DictionaryEnumVO> keyValueList = new ArrayList<>();
            Class cls = Class.forName("com.flowwork.api.enums." + menuType);
            Method method = cls.getMethod("values");
            IBaseEnum inter[] = (IBaseEnum[]) method.invoke(null, null);
            for (IBaseEnum enumMessage : inter) {
                DictionaryEnumVO vo = new DictionaryEnumVO();
                vo.setValue(enumMessage.toString());
                vo.setLabel(enumMessage.getDescription());
                keyValueList.add(vo);
            }
            return R.newOk(keyValueList);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return R.newError(e.getMessage());
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            return R.newError(e.getMessage());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            return R.newError(e.getMessage());
        } catch (InvocationTargetException e) {
            e.printStackTrace();
            return R.newError(e.getMessage());
        }

    }

    /**
     * 批量获取枚举字典信息
     *
     * @param batchMenuType
     * @return
     */
    public R<Map<String, List<DictionaryEnumVO>>> getBatchDictionaryEnum(BatchDicEnumReq batchMenuType) {
        Map<String, List<DictionaryEnumVO>> data = new HashMap<>();
        for (String str : batchMenuType.getEnumType()) {
            R<List<DictionaryEnumVO>> result = getDictionaryEnum(str);
            if (result.getCode() == 0) {
                data.put(str, result.getData());
            } else {
                return R.newError(result.getMsg());
            }
        }
        return R.newOk(data);
    }
}
